package at.falb.games.alcatraz.api.server;

import java.io.Serializable;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import at.falb.games.alcatraz.api.common.IGameConstants;
import at.falb.games.alcatraz.api.common.PlayerUnit;

public class PlayerBuffer implements Serializable {

	private static final long serialVersionUID = 5583222978860902464L;

	private Map<Integer, PlayerUnit> players;

	public PlayerBuffer() {
		players = new HashMap<Integer, PlayerUnit>();
	}

	public int getNbOfPlayers() {
		return players.size();
	}

	public boolean find(String player) throws ServerException {
		if (player == null || player.trim().isEmpty())
			throw new ServerException(IGameConstants.INVALID_NAME);
		boolean findPlayer = false;
		for (Iterator<PlayerUnit> it = getRegisteredPlayers().iterator(); it.hasNext();) {
			if (player.equals(it.next().getClientName()))
				findPlayer = true;
		}
		return findPlayer;
	}

	public boolean find(PlayerUnit player) throws ServerException {
		if (players.containsKey(player.getClientId()))
			return true;
		return find(player.getClientName());
	}

	public void addPlayer(PlayerUnit player) {
		players.put(player.getClientId(), player);
	}

	public void removePlayer(PlayerUnit player) {
		players.remove(player);
	}

	public List<PlayerUnit> getRegisteredPlayers() {
		return new ArrayList<PlayerUnit>(players.values());
	}
}
